package cloud_mqtt

import (
	"fmt"
	MQTT "github.com/eclipse/paho.mqtt.golang"
	"miomp-terminal-suite/backend/global"
	mqttHandler "miomp-terminal-suite/backend/handler/mqtt"
	"miomp-terminal-suite/backend/log"
	"miomp-terminal-suite/backend/pkg/mqtt"
	"miomp-terminal-suite/backend/utils/hash"
)

// define a function for the default message handler
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	log.LOG.Info(fmt.Sprintf("TOPIC: %s", msg.Topic()))
	log.LOG.Info(fmt.Sprintf("MSG: %s", msg.Payload()))
}

func Init() {
	//create a ClientOptions struct setting the broker address, client id, turn
	//off trace output and set the default message handler
	opts := MQTT.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%s:%d", global.CONF.CloudMqtt.Host, global.CONF.CloudMqtt.Port))
	opts.SetUsername(global.CONF.CloudMqtt.Username)
	opts.SetPassword(global.CONF.CloudMqtt.Password)
	clientId := global.CONF.AppDetailConfig.Code + "_" + hash.GenerateUUID()
	opts.SetClientID(clientId)
	opts.SetDefaultPublishHandler(f)

	//create and start a client using the above ClientOptions
	c := MQTT.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		log.LOG.Error("CLOUD_MQTT连接失败", log.U.ErrorFiled(token.Error()))
	} else {
		log.LOG.Info(fmt.Sprintf("CLOUD_MQTT连接成功，连接地址，tcp://%s:%d，连接名称:%s", global.CONF.CloudMqtt.Host, global.CONF.CloudMqtt.Port, clientId))
	}

	global.CloudMqtt = &mqtt.MQTT{Client: c}

	mqttHandler.InitSubscribe()

	for _, handler := range mqtt.CloudSubHandlers() {
		if token := c.Subscribe(handler.Topic, handler.Qos, handler.MsgHandler); token.Wait() && token.Error() != nil {
			log.LOG.Error("CLOUD_MQTT订阅失败", log.U.ErrorFiled(token.Error()))
		}
	}

}
